package textTranslateModel

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"myproject/config"
	"net/http"
	"net/url"
	"sort"
	"strings"
	"time"
)

// 配置信息
const (
	requestURL = "https://mt.cn-hangzhou.aliyuncs.com/"
	//	SourceLanguage = "en"      // 源语言
	//	TargetLanguage = "zh"      // 目标语言
	FormatType = "text"    // 文本格式
	Scene      = "general" // 翻译场景
)

// 需要翻译的文本（全局变量）
// var SourceText = "Hello, this is a test translation using Qwen-MT API."

func Qwen_mt_plus(SourceText string, SourceLanguage string, TargetLanguage string) string {
	// 生成时间戳
	log.Println("text:", SourceText, "from", SourceLanguage, "to", TargetLanguage)
	timestamp := time.Now().UTC().Format("2006-01-02T15:04:05Z")

	// 构建公共参数
	params := map[string]string{
		"Format":           "JSON",
		"Version":          "2018-10-12",
		"SignatureMethod":  "HMAC-SHA1",
		"SignatureVersion": "1.0",
		"AccessKeyId":      config.AppConfig.AliyunTranslate.KeyID,
		"Timestamp":        timestamp,
		"SignatureNonce":   fmt.Sprintf("%d", time.Now().UnixNano()),
		"Action":           "TranslateGeneral",
	}

	// 添加业务参数
	params["FormatType"] = FormatType
	params["SourceLanguage"] = SourceLanguage
	params["TargetLanguage"] = TargetLanguage
	params["SourceText"] = SourceText
	params["Scene"] = Scene

	// 生成签名并添加到参数中
	params["Signature"] = generateSignature1(params, config.AppConfig.AliyunTranslate.KeySecret)

	// 发送HTTP请求
	resp, err := sendRequest1(params)
	if err != nil {
		fmt.Printf("请求失败: %v\n", err)
		return "fail"
	}
	log.Println("生成翻译结果:", resp)
	// 输出翻译结果
	//fmt.Println("翻译结果:")
	//fmt.Println(resp)
	return resp
}

// 生成API签名
func generateSignature1(params map[string]string, secret string) string {
	// 1. 按字典序排序参数名
	keys := make([]string, 0, len(params))
	for k := range params {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	// 2. 构建规范化请求字符串
	var paramStrs []string
	for _, k := range keys {
		// 使用阿里云要求的编码方式
		encodedKey := encodeParameter1(k)
		encodedValue := encodeParameter1(params[k])
		paramStrs = append(paramStrs, fmt.Sprintf("%s=%s", encodedKey, encodedValue))
	}
	canonicalizedQueryString := strings.Join(paramStrs, "&")

	// 3. 构建字符串ToSign
	stringToSign := fmt.Sprintf("POST&%%2F&%s", encodeParameter1(canonicalizedQueryString))

	// 4. 计算HMAC-SHA1签名
	secretKey := secret + "&"
	h := hmac.New(sha1.New, []byte(secretKey))
	h.Write([]byte(stringToSign))
	signatureBytes := h.Sum(nil)

	// 5. Base64编码
	return base64.StdEncoding.EncodeToString(signatureBytes)
}

// 阿里云要求的特殊编码函数
func encodeParameter1(s string) string {
	// 使用RFC3986标准进行编码
	result := url.QueryEscape(s)
	// 替换特殊字符为阿里云要求的格式
	result = strings.ReplaceAll(result, "+", "%20")
	result = strings.ReplaceAll(result, "*", "%2A")
	result = strings.ReplaceAll(result, "%7E", "~")
	return result
}

// 发送HTTP请求
func sendRequest1(params map[string]string) (string, error) {
	// 构建请求URL和表单数据
	//requestURL := "https://mt.cn-hangzhou.aliyuncs.com/"

	// 构建表单数据，使用正确的编码方式
	var formData bytes.Buffer
	for k, v := range params {
		if formData.Len() > 0 {
			formData.WriteByte('&')
		}
		formData.WriteString(encodeParameter1(k))
		formData.WriteByte('=')
		formData.WriteString(encodeParameter1(v))
	}

	// 创建HTTP POST请求
	req, err := http.NewRequest("POST", requestURL, &formData)
	if err != nil {
		return "", err
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	// 处理响应
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("HTTP错误: %s, 响应: %s", resp.Status, string(body))
	}

	// 解析JSON响应
	var result map[string]interface{}
	if err := json.Unmarshal(body, &result); err != nil {
		return string(body), nil // 返回原始响应
	}

	// 提取翻译结果
	if data, ok := result["Data"].(map[string]interface{}); ok {
		if transResult, ok := data["Translated"].(string); ok {
			return transResult, nil
		}
	}

	return string(body), nil
}
